import { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import React from "react";
import styles from "./style.module.less";
import { Breadcrumb, Empty, Input, Spin } from "antd";
import moment from "moment";
import { useLocation } from "react-router-dom";
import baseService from "@service/baseService";
import logoUrl from "@assets/logo.jpg";
import fireUrl from "@assets/fire.png";
import pdf1 from "@assets/pdf1.png";
import PdfViewer from "@components/PdfViewer";
import app, { appKey } from "../../constant/index";

const { Search } = Input;

const handlePathstr = (path) => {
  return path?.replace(
    "https://edu-platform-file.oss-cn-hangzhou.aliyuncs.com",
    "/mine"
  );
};

const PDFLayout = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [curSubjectDetail, setCurSubjectDetail] = useState({});
  const [activeTab, setActiveTab] = useState(0);
  const [activeTabName, setActiveTabName] = useState("");
  const [courseList, setCourseList] = useState([]);
  const [isRecommandList, setIsRecommandList] = useState([]);
  const [pageLoading, setPageLoading] = useState(false);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [searchTxt, setSearchTxt] = useState("");
  const playerRef = React.useRef(null);
  const radmonTime = new Date().getTime();
  const [viderourl, setViderourl] = useState("");

  useEffect(() => {
    getRecommandSubjectInfo();
    if (location?.state?.item) {
      setCurSubjectDetail(location.state.item);
    }
    handleSubjectList();
  }, []);
  
  useEffect(() => {
    if (location?.state?.item) {
      setCurSubjectDetail(location.state.item);

      setViderourl(location.state.videoUrl);
    }
  }, [location?.state?.item]);

  useEffect(() => {
    courseList?.map((item, idx) => {
      if (item.id == curSubjectDetail.subjectId) {
        setActiveTab(Number(idx) + 1);
        setActiveTabName(item.name);
      }
    });
  }, [curSubjectDetail, courseList]);

  const videoJsOptions = {
    // 自动播放：为true时，加载完毕自动播放
    autoplay: false,
    // 播放器子控件是否显示：为true时显示暂停、播放速率等按钮
    controls: true,
    // 响应性：为true时，播放视频进度条会自动移动
    responsive: true,
    // 流式布局：为true时尽可能大得填满父标签的剩余空间
    fluid: true,
    // 视频源
    sources: [
      {
        // 视频文件的路径，可以是一个前端相对路径、后台视频文件URL、直播源等
        src: handlePathstr(curSubjectDetail?.fileUrl),
        // src: 'http://cloud.chan3d.com/cdn/website/mp3/1.mp3',
        // 视频源类型
        type: "video/mp4",
      },
    ],
  };
  // 播放器实例化完成后的事件动作，注意！不是视频加载成功
  const handlePlayerReady = (player) => {
    playerRef.current = player;
    // 播放器的子事件在这里定义

    player.on("canplaythrough", () => {
      console.log("视频加载完成！");
    });

    player.on("error", () => {
      console.log(`视频文件加载失败，请稍后重试！`);
    });

    player.on("stalled", () => {
      console.log(`网络异常，请稍后重试！`);
    });
  };

  const onSearch = () => {
    navigate("/searchPage", { state: { keyWord: searchTxt } });
  };

  const onKeyWordChange = (e) => {
    setSearchTxt(e?.target?.value);
  };

  const getRecommandSubjectInfo = () => {
    try {
      setPageLoading(true);
      baseService
        .get(`/edu/subject/file/page?isRecommand=1`)
        .then((res) => {
          if (res.code == 0) {
            setIsRecommandList(res?.data?.list);
          }
        })
        .finally(() => {
          setPageLoading(false);
        });
    } catch (error) {}
  };

  const handleSubjectList = async () => {
    try {
      baseService.get("/edu/subject/list").then((res) => {
        if (res.code == 0) {
          setCourseList(res.data);
        }
      });
    } catch (error) {}
  };

  const handleTabClick = (nav, idx) => {
    if (idx == 0) {
      navigate("/subjectRecommad");
      return;
    }
    setActiveTab(idx);
    navigate("/subjectList", { state: { name: nav.name, idx: idx } });
  };

  const viewDetail = (result = {}) => {
    const videoUrl = `${handlePathstr(result?.fileUrl)}`;
    try {
      navigate("/acticleDetail", { state: { item: result, videoUrl } });
      baseService.put(`/edu/subject/file/2/${result.id}/count`);
    } catch (error) {}
  };

  const downloadFile = () => {
    setDownloadLoading(true);
    const { fileUrl, title } = curSubjectDetail;
    // 生成PDF的代码
    const link = document.createElement("a");
    link.href = handlePathstr(fileUrl);
    link.setAttribute("download", title);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    setTimeout(() => {
      setDownloadLoading(false);
    }, 1000);
  };

  return (
    <div className={styles.aticleDetailWrapper}>
      <div className={styles.contentWrapper}>
        <Breadcrumb
          className={styles.breadCrumbWrapper}
          items={[
            {
              title: <Link to="/home">首页</Link>,
            },
            {
              title: <Link to="/subjectList">分类（{activeTabName}）</Link>,
            },
            {
              title: "详情",
            },
          ]}
        />
        <div className={styles.testNameWrapper}>
          <h1 className={styles.testName}>
            <img src={pdf1} alt="" className={styles.pdfLogo} />
            {curSubjectDetail.title?.replace(/\.(mp4|pdf|mp3)$/i, "")}
          </h1>
          {appKey === "LIAN_HUAN_HUA" ? null : (
            <div className={styles.downLoad} onClick={downloadFile}>
              免费下载
            </div>
          )}
        </div>
        <div className={styles.feature}>
          <span className={styles.item}>
            日期：{moment(curSubjectDetail.createDate).format("YYYY-MM-DD")}
          </span>
          <span className={styles.item}>
            浏览量: {curSubjectDetail.viewCount}
          </span>
          <span className={styles.item}>
            下载量：{curSubjectDetail.downloadCount}
          </span>
        </div>

        <div className={styles.pdfWrapper}>
          <div className={styles.pdfViewWrapper}>
            {curSubjectDetail?.fileUrl?.toLowerCase()?.endsWith(".pdf") ? (
              curSubjectDetail?.fileUrl ? (
                <PdfViewer fileUrl={handlePathstr(curSubjectDetail?.fileUrl)} />
              ) : (
                <Empty style={{ margin: "100px 0" }} />
              )
            ) : (
              <>
                <video width="100%" controls>
                  {viderourl ? (
                    <source src={`${viderourl}` + `?timer=${radmonTime}`} />
                  ) : null}
                  Your browser does not support the video ta
                </video>
              </>
            )}
          </div>
          <div className={styles.hotRecommand}>
            <p className={styles.title}>推荐资源</p>
            <div className={styles.recommands}>
              {isRecommandList?.slice(0, 7)?.map((nav, idx) => {
                return (
                  <div
                    className={styles.textWrapper}
                    onClick={() => viewDetail(nav)}
                    key={idx}
                  >
                    <img src={fireUrl} className={styles.hotUrl} alt="" />
                    <span className={styles.txt}>
                      {nav.title?.replace(/\.(mp4|pdf|mp3)$/i, "")}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
      <div className={styles.footer_bg}>
        {/* <img src={logoUrl} alt="" className={styles.logo} /> */}
        <section className={styles.footer_section}>
          <p>
            {app.name} ©2024 版权所有 备案号：
            <a href="https://beian.miit.gov.cn" target="_blank">
              苏ICP备2024130913号
            </a>
          </p>
        </section>
      </div>
      <Spin size="large" spinning={pageLoading} fullscreen />
      <Spin size="large" tip="下载中" spinning={downloadLoading} fullscreen />
    </div>
  );
};
export default PDFLayout;
